package cn.edu.scau.cmi.wuzewei.hibernate.dao;

import java.util.List;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import cn.edu.scau.cmi.wuzewei.hibernate.domain.Student;

public class StudentDAOByHibernate extends BaseHibernateDAO {

	public static final String NAME = "name";
	
	public void save(Student student) {
		try {
			getSession().save(student);
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public void delete(Student student) {
		try {
			getSession().delete(student);
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public Student findById(java.lang.Long id) {
		try {
			Student instance = (Student) getSession().get("cn.edu.scau.cmi.wuzewei.hibernate.domain.Student", id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	@SuppressWarnings("rawtypes")
	public List findByExample(Student instance) {
		try {
			List results = getSession().createCriteria("cn.edu.scau.cmi.wuzewei.hibernate.domain.Student")
					.add(Example.create(instance)).list();
			return results;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	@SuppressWarnings("rawtypes")
	public List findByProperty(String propertyName, Object value) {
		try {
			String queryString = "from Student as model where model." + propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	@SuppressWarnings("rawtypes")
	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	@SuppressWarnings("rawtypes")
	public List findAll() {
		try {
			String queryString = "from Student";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public Student merge(Student detachedInstance) {
		try {
			Student result = (Student) getSession().merge(detachedInstance);
			return result;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void attachDirty(Student instance) {
		try {
			getSession().saveOrUpdate(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void attachClean(Student instance) {
		try {
			getSession().buildLockRequest(LockOptions.NONE).lock(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}
}
